//
//  LLLoginViewController.m
//  LoveLove
//
//  Created by wkf on 2019/3/27.
//  Copyright © 2019 wkf. All rights reserved.
//

#import "LLLoginViewController.h"
#import "LLForgetPasswordViewController.h"
//#import "LLButtonCell.h"
#import "LLThirdLoginView.h"
#import "LLRegisterViewController.h"
//#import "JPUSHService.h"
//#import <RongIMKit/RongIMKit.h>
#import "LLUserInfo.h"
#import "LLLaunchViewController.h"
#import "LLUserInfo.h"
#import "TabBarViewController.h"
#import "LLChannelModel.h"
#import "QWebVC.h"
#import "LLDegegateView.h"
#import "LLUserDelegateVC.h"
@interface LLLoginViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) UIImageView *logoImgView;
@property (strong, nonatomic) UITextField *phoneTextField;
@property (strong, nonatomic) UITextField *passwordTextField;
@property (strong, nonatomic) LLButton *loginBtn;
@property (strong, nonatomic) LLButton *registerBtn;
@property (strong, nonatomic) LLButton *forgetBtn;
@property (strong, nonatomic) LLButton *handlePwdTextFieldBtn;
@property (copy, nonatomic) NSArray *loginBtnImgs;
@property (copy, nonatomic) NSString *phone;
@property (copy, nonatomic) NSString *pwd;
@property (copy, nonatomic) NSString *token;
@property (strong, nonatomic) NSArray *loginUserModels;

@property (assign, nonatomic) BOOL isAgree;
@end

@implementation LLLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [SVProgressHUD dismiss];
    self.isAgree = YES;
    self.leftNavImageName = @"矩形 5 拷贝 3";
    self.loginBtnImgs = @[@"QQ_grey",@"wechat_grey",@"weibo_grey"];
    [self initSubViews];
}

- (void) didClickLeftNavAction
{
    [self.view endEditing:YES];
    TabBarViewController *vc = [TabBarViewController new];
    [UIApplication sharedApplication].delegate.window.rootViewController = vc;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationController.navigationBar.tintColor = UIColor.blackColor;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:LLRegularFont(18)}];
    self.navigationController.navigationBar.barTintColor = UIColor.whiteColor;
    self.navigationController.navigationBar.hidden = NO;
    
}

- (void)initSubViews {
    
    //退出按钮
    
    
    // logo
    CGFloat top = LLScreenWidth < 375 ? 0 : LLScreenHeight*0.1;
    CGFloat left = LLScreenWidth < 375 ? 40 : 50;
    CGFloat logoImgViewW = 83;
    UIImageView *topLogo = [UIImageView new];
    topLogo.frame = CGRectMake((LLScreenWidth - logoImgViewW)/2.0, top, logoImgViewW, logoImgViewW);
    topLogo.image = [UIImage imageNamed:@"logo111"];
    [self.view addSubview:topLogo];
    
    _logoImgView = [UIImageView new];
    _logoImgView.frame = CGRectMake((LLScreenWidth - logoImgViewW)/2.0, topLogo.bottom-17, logoImgViewW, logoImgViewW);
    _logoImgView.image = [UIImage imageNamed:@"logo倒影"];

    [self.view addSubview:_logoImgView];
    
    CGFloat fieldH = LLScreenWidth < 375 ? 40 : 50;
    CGFloat phoneTextFieldTopMargin =  LLScreenWidth < 375 ? 10 : 20;
    // 账号输入框
    _phoneTextField = [UITextField new];
    _phoneTextField.frame = CGRectMake(left, _logoImgView.bottom + phoneTextFieldTopMargin, LLScreenWidth - left * 2, fieldH);
    _phoneTextField.placeholder = @"请输入手机号码";
    _phoneTextField.text = self.phone;
    
    UIView *phoneLeftView = UIView.new;
    phoneLeftView.size = CGSizeMake(fieldH-10, fieldH);
    UIImageView *phoneImgView = [UIImageView new];
    phoneImgView.frame = CGRectMake(10, (fieldH-17)/2.0, 12, 17);
    phoneImgView.image = [UIImage imageNamed:@"手机icon"];
    [phoneLeftView addSubview:phoneImgView];
    
    _phoneTextField.leftView = phoneLeftView;
    _phoneTextField.leftViewMode = UITextFieldViewModeAlways;
    _phoneTextField.tag = 0;
    _phoneTextField.font = [UIFont systemFontOfSize:15];
    _phoneTextField.delegate = self;
    _phoneTextField.tintColor = LLColor(225, 0, 0);
    _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phoneTextField.inputAccessoryView = [UIView new];
    _phoneTextField.text = self.phone;
    _phoneTextField.keyboardType = UIKeyboardTypeASCIICapableNumberPad;
    [_phoneTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_phoneTextField];
    CALayer *line1 = [CALayer layer];
    line1.frame = CGRectMake(left, _phoneTextField.bottom, LLScreenWidth - left * 2, 0.5);
    line1.backgroundColor = LLColorRGB(153).CGColor;
    [self.view.layer addSublayer:line1];
    
    //操作密码输入框的按钮
    _handlePwdTextFieldBtn = [LLButton new];
    _handlePwdTextFieldBtn.frame = CGRectMake(LLScreenWidth-40-left, _phoneTextField.bottom+10, 40, fieldH);
    [_handlePwdTextFieldBtn setImage:[UIImage imageNamed:@"睁眼"] forState:0];
    [_handlePwdTextFieldBtn setImage:[UIImage imageNamed:@"闭眼"] forState:UIControlStateSelected];
    _handlePwdTextFieldBtn.selected = YES;
    [self.view addSubview:_handlePwdTextFieldBtn];
    [_handlePwdTextFieldBtn addTarget:self action:@selector(handlePwdTextFieldBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 密码输入框
    _passwordTextField = [UITextField new];
    _passwordTextField.frame = CGRectMake(left, _phoneTextField.bottom + 10, _handlePwdTextFieldBtn.left-left, fieldH);
    _passwordTextField.placeholder = @"请输入密码";
    
    UIView *pwdLeftView = UIView.new;
    pwdLeftView.size = CGSizeMake(fieldH-10, fieldH);
    UIImageView *pwdImgView = [UIImageView new];
    pwdImgView.frame = CGRectMake(10, (fieldH-15)/2.0, 13, 15);
    pwdImgView.image = [UIImage imageNamed:@"密码icon"];
    [pwdLeftView addSubview:pwdImgView];
    
    _passwordTextField.leftView = pwdLeftView;
    _passwordTextField.leftViewMode = UITextFieldViewModeAlways;
    _passwordTextField.tag = 1;
    _passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _passwordTextField.returnKeyType = UIReturnKeyDone;
    _passwordTextField.delegate = self;
    _passwordTextField.tintColor = LLColor(225, 0, 0);
    _passwordTextField.inputAccessoryView = [UIView new];
    _passwordTextField.secureTextEntry = YES;
    _passwordTextField.keyboardType = UIKeyboardTypeASCIICapable;
    _passwordTextField.font = [UIFont systemFontOfSize:15];
    _passwordTextField.text =self.pwd;
    [_passwordTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_passwordTextField];
    CALayer *line2 = [CALayer layer];
    line2.frame = CGRectMake(left, _passwordTextField.bottom, LLScreenWidth - left * 2, 0.5);
    line2.backgroundColor = LLColorRGB(153).CGColor;
    [self.view.layer addSublayer:line2];
    
    LLDegegateView *delegateView = [[LLDegegateView alloc]initWithFrame:CGRectMake(0, _passwordTextField.bottom + 10, _handlePwdTextFieldBtn.left-left, fieldH)];
    [self.view addSubview:delegateView];
    
   __weak typeof(self) weakSelf = self;
    delegateView.clickBlock = ^(NSInteger type, BOOL isAgree) {
        if (type == 1) {
            LLUserDelegateVC *vc = [LLUserDelegateVC new];
            vc.url = @"http://www.haoaih.com/h5/index/archive?id=1";
            [weakSelf.navigationController pushViewController:vc animated:YES];

        }else if (type == 2){
            LLUserDelegateVC *vc = [LLUserDelegateVC new];
            vc.url = @"http://www.haoaih.com/h5/index/archive?id=2";
            [weakSelf.navigationController pushViewController:vc animated:YES];

        }else{
            weakSelf.isAgree = isAgree;
        }
    };
    // 登录按钮
    CGFloat loginBtnTopMargin = LLScreenWidth < 375 ? 30 : 40;
    _loginBtn = [LLButton new];
    _loginBtn.frame = CGRectMake(left, _passwordTextField.bottom + loginBtnTopMargin, LLScreenWidth - left * 2, 38);
    [_loginBtn setBackgroundColor:LLColor(225, 0, 0)];
    [_loginBtn setTitle:@"登录" forState:0];
    [_loginBtn setTitleColor:[UIColor whiteColor] forState:0];
    _loginBtn.titleLabel.font = [UIFont systemFontOfSize:17];
    _loginBtn.layer.cornerRadius = 19;
    [_loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginBtn];
    
    // 注册按钮
    CGFloat btnW = 80;
    _registerBtn = [LLButton new];
    _registerBtn.frame = CGRectMake((LLScreenWidth-btnW*2)/2.0, _loginBtn.bottom + 10, btnW, 30);
    [_registerBtn setTitle:@"账号注册>" forState:0];
    _registerBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [_registerBtn setTitleColor:LLColor(220, 0, 0) forState:0];
//    [_registerBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [_registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_registerBtn];
    
    CALayer *separateLine = CALayer.layer;
    separateLine.backgroundColor = LLColor(220, 0, 0).CGColor;
    separateLine.frame = CGRectMake(_registerBtn.right, _registerBtn.top+8, 1, 14);
    [self.view.layer addSublayer:separateLine];
    
    // 忘记密码按钮
    _forgetBtn = [LLButton new];
    _forgetBtn.frame = CGRectMake(separateLine.right, _registerBtn.top, btnW, 30);
    [_forgetBtn setTitle:@"忘记密码>" forState:0];
    _forgetBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [_forgetBtn setTitleColor:LLColor(220, 0, 0) forState:0];
//    [_forgetBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [_forgetBtn addTarget:self action:@selector(forgetBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_forgetBtn];


//    UIButton *btns = [LLButton new];
//    btns.frame = CGRectMake((LLScreenWidth-btnW)/2, _forgetBtn.bottom+20, btnW, 30);
//    [btns setTitle:@"《用户协议》" forState:0];
//    btns.titleLabel.font = [UIFont systemFontOfSize:13];
//    [btns setTitleColor:LLColor(220, 0, 0) forState:0];
//    [btns addTarget:self action:@selector(aggrement) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:btns];
    
    // 第三方登录
//    [self initThirdLoginView];
}

- (void) aggrement
{
    QWebVC *vc = [QWebVC new];
    vc.urlString = [NSString stringWithFormat:@"http://www.haoaih.com/h5/index/archive?id=1"];
    vc.showNavBar = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)initThirdLoginView {
    //    if ([QQApiInterface isQQInstalled]) [self.loginBtnImgs addObject:@"QQ-2"];
    //    if ([WXApi isWXAppInstalled]) [self.loginBtnImgs addObject:@"微信"];
    
    NSString *device = [LLHttpTool deviceModelName];
    if ([device isEqualToString:@"iPad"]) return;
    LLThirdLoginView *view = [LLThirdLoginView new];
    view.frame = CGRectMake(0, LLScreenHeight - self.navH - 120, LLScreenWidth, 120);
    view.imgs = self.loginBtnImgs;
    MJWeakSelf
    [view setDidClickBtnBlock:^(NSInteger tag) {
        NSString *imageName = weakSelf.loginBtnImgs[tag];
    }];
    [self.view addSubview:view];
}

- (void)loginBtnClick {
    [LLUserManager login];
    [self loginWithPassword];
}

// 密码登录
- (void)loginWithPassword {
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (_phoneTextField.text.length == 0 ) {
        [self showSVProgressHUDInfoWithsStatus:@"您还未输入手机号~"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    } else if (_passwordTextField.text.length == 0){
        [self showSVProgressHUDInfoWithsStatus:@"您还未输入密码~"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    } else if (!self.isAgree){
        [self showSVProgressHUDInfoWithsStatus:@"请同意用户协议~"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    
    [self sendLoginRequst];
//
//    [self.view endEditing:YES];
//    [SVProgressHUD show];
//    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
//    NSDictionary *dictionary = @{@"mobile":_phoneTextField.text,
//                                 @"password":_passwordTextField.text};
//    [LLHttpTool post:ApiLogin_password params:dictionary success:^(NSDictionary *result) {
//        [SVProgressHUD dismiss];
//
//        self.model = [LLHomeMyViewModel mj_objectWithKeyValues:result[@"data"]];
//        [LLUserManager setUserModelWithDict:result[@"data"]];
//        [LLUserDefaults setObject:_phoneTextField.text forKey:LLUserPhone];
//        [LLUserDefaults setObject:_passwordTextField.text forKey:LLPassword];
//        [LLUserDefaults setObject:self.model.alc forKey:LLCookies];
//        [LLUserDefaults setObject:result[@"data"][@"nickname"] forKey:LLNickName];
//        [LLUserDefaults setObject: self.model.is_vip forKey:LLVip];
//        [LLUserDefaults setObject: self.model.user_id forKey:LLUserId];
//        [LLUserDefaults setObject:self.model.is_private forKey:LL_User_quanxian];
//        [LLUserDefaults setObject:self.model.withdraw_passwd forKey:LLwithdraw_passwd];
//        [LLUserDefaults setObject:self.model.pay_code forKey:LL_pay_code];
//
//        if ([self.model.permission integerValue]<0) {
//            [LLUserDefaults setObject:@"4" forKey:LL_WORKER_TYPE];
//        } else {
//            [LLUserDefaults setObject:self.model.permission forKey:LL_WORKER_TYPE];
//        }
//
//        [LLUserDefaults setObject:@"0" forKey:LLIsShareUsers];
//        // 登录成功的通知
//        [LLNotificationCenter postNotificationName:@"loginSuccessNoti" object:nil];
//
//        for (int i=0; i<4; i++) {
//            if (i==0) {
//                if ([self.model.is_share_0 isEqualToString:@"1"]) {
//                    [LLUserDefaults setObject:@"1" forKey:LLIsShareUsers];
//                    break;
//                }
//            } else if (i==1) {
//                if ([self.model.is_share_1 isEqualToString:@"1"]) {
//                    [LLUserDefaults setObject:@"1" forKey:LLIsShareUsers];
//                    break;
//                }
//            }  else if (i==2) {
//                if ([self.model.is_share_2 isEqualToString:@"1"]) {
//                    [LLUserDefaults setObject:@"1" forKey:LLIsShareUsers];
//                    break;
//                }
//            }  else if (i==3) {
//                if ([self.model.is_share_3 isEqualToString:@"1"]) {
//                    [LLUserDefaults setObject:@"1" forKey:LLIsShareUsers];
//                    break;
//                }
//            }
//        }
//        [LLUserDefaults synchronize];
//
//        [JPUSHService setAlias:[NSString stringWithFormat:@"%@",self.model.user_id] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
//            NSLog(@"%ld    %@    %ld",(long)iResCode,iAlias,(long)seq);
//        } seq:200];
//
//
//        LLLocationModel *locationModel = [LLUserManager getSelectedLocation];
//        NSSet * set ;
//        if ([[LLUserDefaults objectForKey:LLISJPush] isEqualToString:@"0"]) {
//            NSString *sss = [NSString stringWithFormat:@"C%@",locationModel.citycode];
//            set = [[NSSet alloc] initWithObjects:@"stop_push",sss, nil];
//            [LLUserDefaults setObject:@"0" forKey:LLISJPush];
//        } else {
//            NSString *sss = [NSString stringWithFormat:@"C%@",locationModel.citycode];
//            set = [[NSSet alloc] initWithObjects:@"allow_push",sss, nil];
//            [LLUserDefaults setObject:@"1" forKey:LLISJPush];
//        }
//        [JPUSHService setTags:set completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
//            if (iResCode == 0) {
//                NSLog(@"设置标签%ld %@",(long)iResCode,iTags);
//            }
//        } seq:200];
//
//
//        [self dismissViewControllerAnimated:YES completion:nil];
//
//        [LLHttpTool post:ApiToken params:nil success:^(NSDictionary *result111) {
//            MJWeakSelf
//            [[RCIMClient sharedRCIMClient] connectWithToken:result111[@"data"][@"token"] success:^(NSString *userId) {
//                NSLog(@"融云登录成功");
//                RCUserInfo *userInfo = [[RCUserInfo alloc]init];
//                userInfo.name = weakSelf.model.nickname;
//                userInfo.userId = weakSelf.model.user_id;
//                NSString *aa = [NSString stringWithFormat:@"%@%@.png",LLBaseHeadAliURL,weakSelf.model.user_id];
//                userInfo.portraitUri =  aa;
//                //                if ([self.model.head_img containsString:@"http"]) {
//                //                    userInfo.portraitUri =  self.model.head_img;
//                //                } else {
//                //                    userInfo.portraitUri = [NSString stringWithFormat:@"%@%@", LLBaseURL, self.model.head_img];
//                //                }
//                [[RCIM sharedRCIM] setCurrentUserInfo:userInfo];
//                [[RCIM sharedRCIM] setEnableMessageAttachUserInfo:YES];
//            } error:^(RCConnectErrorCode status) {
//                NSLog(@"融云登录失败");
//            } tokenIncorrect:^{
//                NSLog(@"token过期");
//            }];
//        } failure:^(NSString *msg111) {
//            [SVProgressHUD dismiss];
//            [SVProgressHUD showErrorWithStatus:msg111];
//        }];
//    } failure:^(NSString *msg) {
//        [SVProgressHUD dismiss];
//        [SVProgressHUD showErrorWithStatus:msg];
//        _passwordTextField.text = @"";
//    }];
}

// 注册
- (void)registerBtnClick {
    LLRegisterViewController *vc = LLRegisterViewController.new;
    vc.tagArray  = self.tagArray;
    [self.navigationController pushViewController:vc animated:YES];
}

// 忘记密码
- (void)forgetBtnClick {
    LLForgetPasswordViewController *vc = [LLForgetPasswordViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)handlePwdTextFieldBtnClick:(LLButton *)btn {
    _handlePwdTextFieldBtn.selected = !_handlePwdTextFieldBtn.isSelected;
    [self.passwordTextField setSecureTextEntry:!self.passwordTextField.secureTextEntry];
    NSString *tempStr = _passwordTextField.text;
    _passwordTextField.text = nil;
    _passwordTextField.text = tempStr;
}

// 快速注册
//- (void)registerAccountWithPermisson:(NSInteger)permission {
//    if (!self.token) return;
//    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    param[@"mobile"] = self.phone;
//    param[@"token"] = self.token;
//    param[@"permission"] = @(permission);
//    [self showSVProgressHUD];
//    [LLHttpTool post:ApiRegisterFast params:param success:^(NSDictionary *result) {
//        [SVProgressHUD dismissWithDelay:0.3];
//    } failure:^(NSString *msg) {
//        [SVProgressHUD showErrorWithStatus:msg];
//    }];
//}

- (void)textFieldChange:(UITextField *)textField {
    if (textField.markedTextRange == nil) {
        if (textField.tag == 0) {
            if (textField.text.length >= 11) {
                textField.text = [textField.text substringToIndex:11];
            }
            self.phone = textField.text;
            if (textField.text.length < 11) {
                _passwordTextField.text = @"";
                self.pwd = _passwordTextField.text;
            }
        } else {
            if (textField.text.length >= 16) {
                textField.text = [textField.text substringToIndex:16];
            }
            self.pwd = textField.text;
        }
        BOOL isPwd = self.pwd.length >= 6;
        if (self.phone.length == 11 && isPwd) {
            _loginBtn.enabled = YES;
            _loginBtn.backgroundColor = LLMainColor;
        } else {
            _loginBtn.enabled = NO;
            _loginBtn.backgroundColor = LLMainDisabledColor;
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return YES;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}


#pragma mark---手机登录请求
-(void)sendLoginRequst{

    NSDictionary *dic = @{@"edu_id":@"4",@"mobile":self.phone,@"pwd":self.pwd};
    [self showSVProgressHUD];
    [LLHttpTool post:LLHOST headParams:nil params:dic success:^(NSDictionary *result) {
        NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
        [userdefault setObject:self.phone forKey:@"phone"];
        [userdefault setObject:self.pwd forKey:@"pwd"];
         [userdefault setObject:self.pwd forKey:@"interest"];
       LLUserInfo *user = [[LLUserInfo alloc] initWithDic:result[@"data"]];
        
        [LLUserInfo saveUserInfoToLocal:result[@"data"]];

        user.isLogin = YES;

        [LLUserDefaults setObject:@"1" forKey:@"firstUse"];
       [LLUserDefaults setObject:result[@"data"][@"user_interest"] forKey:@"user_interest"];
        [ userdefault setObject:user.user_id forKey:@"user_id"];
        [ userdefault setObject:user.user_random forKey:@"user_random" ];
         [LLUserDefaults synchronize];
        [self showSVProgressHUDInfoWithsStatus:@"登录成功~"];
        [SVProgressHUD dismissWithDelay:1];
        [self.navigationController popViewControllerAnimated:YES];
        TabBarViewController *vc = [TabBarViewController new];
        [UIApplication sharedApplication].delegate.window.rootViewController = vc;
    } failure:^(NSString *msg) {
        [SVProgressHUD showErrorWithStatus:msg];
    }];
}


#pragma mark --- dealloc
- (void)dealloc {
    [LLNotificationCenter removeObserver:self];
}

@end
